package xyz.ddlnt.servicemg.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import xyz.ddlnt.commonutil.util.Argon2Util;
import xyz.ddlnt.commonutil.util.RandomUtil;
import xyz.ddlnt.model.entity.AdminInfo;
import xyz.ddlnt.servicemg.mapper.AdminMapper;
import xyz.ddlnt.servicemg.service.AdminService;

import java.time.LocalDateTime;

/**
 * @author ZZULI_SE 210910
 * @data 2025/5/9 15:43
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdminInfo> implements AdminService {

    @Resource
    private AdminMapper adminMapper;


    @Override
    public String login(AdminInfo adminInfo) {

        LambdaQueryWrapper<AdminInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminInfo::getUsername, adminInfo.getUsername())
                .select(AdminInfo::getId, AdminInfo::getPassword);
        AdminInfo admin = adminMapper.selectOne(queryWrapper);
        if (Argon2Util.verifyPassword(admin.getPassword(), adminInfo.getPassword())) {
            StpUtil.login(admin.getId());
            return StpUtil.getTokenValue();
        }
        return "";
    }

    @Override
    public Boolean register(AdminInfo adminInfo) {
        if (adminInfo.getUsername() == null || adminInfo.getUsername().isEmpty()) {
            throw new RuntimeException("用户昵称不能为空");
        }
        if (adminInfo.getPassword() == null || adminInfo.getPassword().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        Long adminId = RandomUtil.generate12DigitRandomNumber();
        adminInfo.setId(adminId);
        adminInfo.setAddTime(LocalDateTime.now());
        adminInfo.setPassword(Argon2Util.hashPassword(adminInfo.getPassword()));
        adminMapper.insert(adminInfo);
        return true;
    }
}
